package com.ewayde.base.statemachine.impl;

import com.ewayde.base.statemachine.State;
import com.ewayde.base.statemachine.StateMachine;
import com.ewayde.base.statemachine.Transition;

import java.util.List;
import java.util.Map;

/**
 * @author yanwei li create  2024-05-28 19:22
 */
public class StateMachineImpl<S,E,C> implements StateMachine<S, E, C> {
    /* 状态机 ID */
    private String machineId;

    private final Map<S, State<S,E,C>> stateMap;

    public StateMachineImpl(Map<S, State<S, E, C>> stateMap) {
        this.stateMap = stateMap;
    }

    /**
     * 验证是否可以在此状态上发生（fast fail 思想 ）
     *
     * @param sourceStateId
     * @param event
     */
    @Override
    public boolean verify(S sourceStateId, E event) {
        return false;
    }

    /**
     * 状态机处理事件
     *
     * @param sourceState 事件前的状态
     * @param event       事件
     * @param context     上下文
     * @return target State
     */
    @Override
    public S fireEvent(S sourceState, E event, C context) {
        State<S, E, C> sState = stateMap.get(sourceState);
        final List<Transition<S, E, C>> eventTransitions = sState.getEventTransitions(event);
        if (eventTransitions == null || eventTransitions.size() == 0) {
            return null;
        }


        for (Transition<S, E, C> eventTransition : eventTransitions) {
            if (eventTransition !=null){
                final State<S, E, C> transit = eventTransition.transit(context, true);
                return transit.getId();
            }
        }
        return null;
    }

    /**
     * 获取状态机 CODE
     */
    @Override
    public String getMachineId() {
        return machineId;
    }


    public void setMachineId(String machineId) {
        this.machineId = machineId;
    }
}
